﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.IO.Ports;

namespace PIM_ATE.rflight
{
    class ClsRfPimCmd
    {//纳特设备指令集
        /* 控软件port=50000，直接控设备ip=192.168.1.68  prot=5044  双网卡电脑   本机测试 127.0.0.1 */
        //const int PORT = 5044;
        const int TIMEOUT = 100;
        const string NEW_LINE = "\n";
        bool m_isDebug = false;
        string m_error;
        TcpClient m_tcpObj;
        NetworkStream m_netObj;
        double ranMax = -115;
        double ranMin = -120;
        double Tx1 = 0;
        double Tx2 = 0;
        string m_msg = "";
        public ClsRfPimCmd(bool isDebug = false)
        {
            SetDebug(isDebug);
        }
        public void SetDebug(bool isDebug)
        {
            m_isDebug = isDebug;
        }
        public bool SetTxPower(double tx1, double tx2)
        {
            Tx1 = tx1;
            Tx2 = tx2;
            return true;
        }
        public void SetDebugMaxMin(double max, double min)
        {
            if (max != 0 && min != 0)
            {
                ranMax = max;
                ranMin = min;
            }
            else
            {
                ranMax = -115;
                ranMin = -120;
            }
        }
        public bool Connect(string ip, int port = 50000)
        {/* 控软件port=50000，直接控设备ip=192.168.1.68  prot=5044  */
            if (m_isDebug) return true;
            try
            {
                m_tcpObj = new TcpClient();
                m_tcpObj.Connect(ip, port);
                m_netObj = m_tcpObj.GetStream();
                m_tcpObj.SendTimeout = 1000;
                m_tcpObj.ReceiveTimeout = 1000;
                return true;
            }
            catch (Exception ex)
            {
                m_error = ex.Message;
                return false;
            }
        }
        public void Close()
        {
            if (m_tcpObj != null)
            {
                if (m_tcpObj.Connected)
                {
                    m_netObj.Close();
                }
                m_tcpObj.Close();
            }
        }
        bool sendMsg(string cmd, out string msg)
        {
            msg = "";
            //byte[] message = Encoding.ASCII.GetBytes(cmd);
            //try
            //{
            //    m_netObj.Write(message, 0, message.Length);
            //}
            //catch (Exception ex)
            //{
            //    m_error += "sendMsg: net error" + ex.Message; return false;
            //}
            //return isNAK(out msg);

            byte[] sendBytes = Encoding.UTF8.GetBytes(cmd);
            for (int count = sendBytes.Length; count > 0; )
            {
                try
                {

                    if (m_netObj.CanWrite)
                    {
                        if (count <= m_tcpObj.SendBufferSize)
                        {
                            m_netObj.Write(sendBytes, sendBytes.Length - count, count);
                            count = 0;
                            break;
                        }
                        else
                        {
                            m_netObj.Write(sendBytes, sendBytes.Length - count, m_tcpObj.SendBufferSize);
                            count -= m_tcpObj.SendBufferSize;
                        }
                    }
                    else
                    {
                        return false;
                    }
                }
                catch (Exception ex)
                {
                    m_error += "sendMsg: net error" + ex.Message; return false;
                }

            }
            return isNAK(out msg);
            //return true;
        }
        string readMsg()
        {
            //int count = 0;
            //byte[] read = new byte[512];
            //for (int i = 0; i < TIMEOUT; i++)
            //{
            //    if (m_tcpObj.Available > 0)
            //    {
            //        try
            //        {
            //            count = m_netObj.Read(read, 0, read.Length);
            //        }
            //        catch (Exception ex)
            //        {
            //            m_error = "readMsg: net error" + ex.Message;
            //        }
            //        break;
            //    }
            //    if (i == TIMEOUT - 1)
            //    {
            //        m_error = "readMsg: timeout";
            //        return "";
            //    }
            //    //Thread.Sleep(100);
            //}
            //string ret = Encoding.ASCII.GetString(read, 0, count);
            //return ret;


            string buf = null;
            int result = 0, value;

            byte[] recivebytes = new byte[m_tcpObj.ReceiveBufferSize];
            while (true)
            {
                try
                {
                    if (m_netObj.CanRead)
                    {
                        Array.Clear(recivebytes, 0, recivebytes.Length);
                        value = m_netObj.Read(recivebytes, 0, (int)m_tcpObj.ReceiveBufferSize);
                        if (value > 0)
                        {
                            result += value;
                            buf += Encoding.UTF8.GetString(recivebytes).TrimEnd('\0');
                        }

                        //if (result >= length)
                        //{
                        //    break;
                        //}

                        if (recivebytes[value - 1] == '\n')
                        {
                            break;
                        }
                    }
                }
                catch
                {
                    break;
                }
            }
            return buf;

        }
        public bool setFreqBand(int index = 0)
        {//设置系统频段 -- 700索引0，800索引1，900索引2，1800索引3，2100索引5，2600索引6  "SYST:FREQ:BAND 0\n"
            if (m_isDebug) return true;
            m_error = "";
            string cmd = string.Format("FREQ:BAND {0}\n", index);
            m_msg = "";
            return sendMsg(cmd, out m_msg);
        }
        public bool setMeasMode(bool isREFL)
        {//设置系统测量模式（端口号）   设置系统测量模式为反射 "SYST:MEAS:MODE REFL\n"
            if (m_isDebug) return true;
            m_error = "";
            string cmd = "";
            if (isREFL)
            {
                cmd = string.Format("SYST:MODE REFL\n");
            }
            else
            {
                cmd = string.Format("SYST:MODE TRAN\n");
            }
            m_msg = "";
            return sendMsg(cmd, out m_msg);
        }
        public bool setFreqMode(bool isFIX = true)
        {//设置点频\扫频模式 "FREQ:MODE FIX\n"
            //if (m_isDebug) return true;
            //m_error = "";
            //string cmd = "";
            //if (isFIX)
            //    cmd = string.Format("FREQ:MODE FIX\n");
            //else
            //    cmd = string.Format("FREQ:MODE SWE\n");
            //m_msg = "";
            //return sendMsg(cmd, out m_msg);
            return true;
        }
        public bool setCarrFreq(double f1, double f2, string unit = "mhz")
        {//点频设置载波1、2频率;扫频设置起始终止频段范围  单位MHz  "CARR:FREQ 1805.0,1880.0\n"
            if (m_isDebug) return true;
            m_error = "";
            f1 = ToMhz(f1, unit);
            f2 = ToMhz(f2, unit);
            string cmd = String.Format("CARR{0}:FREQ {1:000.000} MHz\n", 1, f1);
            m_msg = "";
            sendMsg(cmd, out m_msg);
            cmd = String.Format("CARR{0}:FREQ {1:000.000} MHz\n", 2, f2);
            m_msg = "";
            return sendMsg(cmd, out m_msg);

        }
        double ToMhz(double freq, string unit)
        {
            if (unit.ToLower() == ("ghz"))
            {
                freq *= 1000;
            }

            else if (unit.ToLower() == ("khz"))
            {
                freq /= 1000;
            }

            else if (unit.ToLower() == ("hz"))
            {
                freq /= 1000 * 1000;
            }

            else//默认为mhz
            { }
            return Math.Round(freq, 1);
        }
        public bool setPimOrd(int order = 3)
        {//设置系统互调阶数位3："SYST:PIM:ORD 3\n"
            if (m_isDebug) return true;
            m_error = "";
            string cmd = string.Format("IM:ORD {0}\n", order);
            m_msg = "";
            return sendMsg(cmd, out m_msg);
        }
        public bool setCarrPow(double power = 43.00)
        {//设置载波1、2的功率为43.00 dBm："CARR:POW 43.00\n"
            //Tx1 = Tx2 = power;
            //if (m_isDebug) return true;
            //m_error = "";
            //string cmd = string.Format("CARR:POW {0}\n", Math.Round(power, 2));
            //m_msg = "";
            //return sendMsg(cmd, out m_msg);
            return true;
        }

        public bool GetCarrierPowerRange(ref double min, ref double max)
        {
            if (m_isDebug) { min = 0; max = 99; return true; }
            string cmd = "CARR:POW:LIM?\n";
            m_error = cmd;
            if (!sendMsg(cmd, out m_msg))
            {
                m_error = "CARR:POW:LIM?: sendMsg net error";
                return false;
            }
            string rbuf = m_msg;
            string[] para = rbuf.Split(',');
            if (para.Length != 2)
            {
                return false;
            }

            try
            {
                min = Convert.ToDouble(para[0]);
            }
            catch
            {
                return false;
            }

            try
            {
                max = Convert.ToDouble(para[1]);
            }
            catch
            {
                return false;
            }

            return true;
        }

        public bool getCarrPow(int source, ref double p1, ref double p2)
        {//查询载波功率："CARR:POW?\n"

            if (m_isDebug)
            {
                p1 = Tx1;
                p2 = Tx2;
                return true;
            }
            m_error = "";
            string cmd = String.Format("CARR{0}:POW?\n", source);
            m_msg = "";

            if (!sendMsg(cmd, out m_msg))
            {
                m_error = "CARR:POW?: sendMsg net error";
                return false;
            }
            else
            {
                try
                {
                    string[] reply = m_msg.Split(' ');
                    if (source == 1)
                    {
                        p1 = Convert.ToDouble(reply[0]);
                    }
                    else
                    {
                        p2 = Convert.ToDouble(reply[0]);
                    }
                }
                catch
                {
                    return false;
                }
            }
            return true;
        }

        public bool setSystPimUnit(ImUnit unit = ImUnit.dBm)
        {//设置系统互调单位为dBm："SYST:PIM:UNIT dBm\n"
            if (m_isDebug) return true;
            m_error = "";
            string cmd = "";
            if (unit == ImUnit.dBm)
                cmd = string.Format("SYST:PIM:UNIT dBm\n");
            else
                cmd = string.Format("SYST:PIM:UNIT dBc\n");
            m_msg = "";
            return sendMsg(cmd, out m_msg);
        }
        public bool setMeasTime(int second = 5)
        {//设置系统测量时间为5秒："SYST:MEAS:TIME 5\n"
            //if (m_isDebug) return true;
            //m_error = "";
            //string cmd = string.Format("SYST:MEAS:TIME {0}\n", second);
            //m_msg = "";
            //return sendMsg(cmd, out m_msg);
            return true;
        }
        public bool setInitCont(bool isOpen = true)
        {//设置连续启动模式开启："INIT:CONT ON\n"   仅仅点频有效,开启了会连续测试至时间停止，不开启仅仅测试一个频点
            //if (m_isDebug) return true;
            //m_error = "";
            //string cmd = "";
            //if (isOpen)
            //    cmd = string.Format("INIT:CONT ON\n");
            //else
            //    cmd = string.Format("INIT:CONT OFF\n");
            //m_msg = "";
            //return sendMsg(cmd, out m_msg);
            return true;
        }
        public bool setInitImm(bool output = true)
        {//设置立即启动测试："INIT:IMM\n"
            /*（点频模式下，立即启动命令执行后，如果连续启动模式开启，则在系统测量时间内，互调仪连续测试；如果连续启动模式关闭，只点频测试一次。）
             	停止测试："OUTP:STAT OFF\n"
             */
            if (m_isDebug) return true;
            m_error = "";
            string cmd = "";
            string outStat = "";
            if (output)
            {
                outStat = "ON";
            }
            else
            {
                outStat = "OFF";
            }
            cmd = String.Format("CARR{0}:OUTP:STAT {1}\n", 1, outStat);
            m_msg = "";
            sendMsg(cmd, out m_msg);
            cmd = String.Format("CARR{0}:OUTP:STAT {1}\n", 2, outStat);
            m_msg = "";
            return sendMsg(cmd, out m_msg);
        }
        public bool getOpc()
        {//连续查询测试完成状态："*OPC?\n"，直至返回状态为1。
            /*正常应答：“X\n”（ 1表示测试完成，0表示测试进行中）异常应答：“NAK\n”*/
            //if (m_isDebug) return true;
            //m_error = "";
            //string cmd = string.Format("*OPC?\n");
            //while (true)
            //{
            //    m_msg = "";
            //    if (!sendMsg(cmd, out m_msg))
            //    {
            //        m_error = "OPC: sendMsg net error";
            //        return false;
            //    }
            //    else
            //    {
            //        if (m_msg == "1\n" || m_msg == "OFF\n")
            //        {
            //            return true;
            //        }
            //        else if (m_msg == "0\n" || m_msg == "ON\n")
            //        {
            //            Thread.Sleep(50);
            //            continue;
            //        }
            //    }
            //}
            return true;
        }
        public bool getOpc_Time()
        {//连续查询测试完成状态："*OPC?\n"，直至返回状态为1。
            /*正常应答：“X\n”（ 1表示测试完成，0表示测试进行中）异常应答：“NAK\n”*/
            //if (m_isDebug) return false;
            //m_error = "";
            //string cmd = string.Format("*OPC?\n");
            //while (true)
            //{
            //    m_msg = "";
            //    if (!sendMsg(cmd, out m_msg))
            //    {
            //        m_error = "OPC: sendMsg net error";
            //        return false;
            //    }
            //    else
            //    {
            //        if (m_msg == "1\n" || m_msg == "OFF\n")
            //        {
            //            return true;
            //        }
            //        else if (m_msg == "0\n" || m_msg == "ON\n")
            //        {
            //            return false;
            //        }
            //    }
            //}
            return true;
        }
        public bool getFixPimData(double freq, ref double dPimResult)
        {//查询点频互调数据："FIX:PIM:DATA?\n"
            /*正常应答：例如“890.0, -122.69\n”（890.0表示互调频率，-122.69表示互调功率）
             * 异常应答：“NAK\n”
             */
            if (m_isDebug)
            {
                Random ran = new Random(Guid.NewGuid().GetHashCode());
                int min = (int)(ranMin * 10);
                int max = (int)(ranMax * 10);
                dPimResult = ran.Next(min, max) / 10 + ran.NextDouble();
                dPimResult = Math.Round(dPimResult, 2);
                return true;
            }
            m_error = "";
            string cmd = string.Format("IM:POW?\n");

            m_msg = "";
            if (!sendMsg(cmd, out m_msg))
            {
                m_error = "result: sendMsg net error";
                return false;
            }
            else
            {
                try
                {
                    string[] reply = m_msg.Split(' ');
                    dPimResult = Convert.ToDouble(reply[0]);
                }
                catch
                {
                    m_error = "result: PimResult error ==>" + m_msg;
                    return false;
                }
            }
            return true;
        }
        public bool setSweStep(double step = 1.0d)
        {//设置扫频步进为1 MHz："SWE:STEP 1.0\n"
            //if (m_isDebug) return true;
            //m_error = "SWE:STEP";
            //string cmd = string.Format("SWE:STEP {0}\n", step);
            //m_msg = "";
            //return sendMsg(cmd, out m_msg);
            return true;
        }

        public bool QueryAlarmStatus(ref byte status)
        {//告警状态
            if (m_isDebug) return true;
            if (!sendMsg("ALAR:STAT?\n", out m_msg))
            {
                return false;
            }

            if (m_msg.Length != 9)
            {
                return false;
            }

            status = 0;
            for (int index = 0; index < 8; index++)
            {
                if ((m_msg[index] > 0x31) || (m_msg[index] < 0x30))
                {
                    return false;
                }

                if (m_msg[index] == 0x31)
                {
                    status |= (byte)(0x01 << (7 - index));
                }
            }

            return true;
        }

        public bool QueryCarrierAtt(int source, ref double att)
        {//衰减量
            if (m_isDebug) return true;
            string tbuf = String.Format("CARR{0}:ATT?\n", source);
            m_msg = ""; m_error = tbuf;
            if (!sendMsg(tbuf, out m_msg))
            {
                return false;
            }
            try
            {
                string[] reply = m_msg.Split(' ');
                att = Convert.ToDouble(reply[0]);
            }
            catch
            {
                return false;
            }

            return true;
        }
        public bool SetCarrierAtt(int source, double att)
        {//衰减器
            if (m_isDebug) return true;
            string tbuf = String.Format("CARR{0}:ATT {1:00.00} dB\n", source, att);
            m_msg = ""; m_error = tbuf;
            if (!sendMsg(tbuf, out m_msg))
            {
                return false;
            }
            if (m_msg != "ACK\n")
            {
                return false;
            }

            return true;
        }

        public bool Carrier1Leveling(double p1)
        {
            if (m_isDebug) return true;
            double att = 31.75, delta = 0;
            int cycle = 3;
            byte status = 0;
            double lev1 = 0, lev2 = 0;

            for (int loop = 0; loop < cycle; loop++)
            {

                if (!QueryAlarmStatus(ref status))
                {
                    if (status == 0X02)
                    {
                        m_error = "Over VSWR Alarm";
                    }
                    else if (status == 0X04)
                    {
                        m_error = "Over Driver Alarm";
                    }
                    return false;
                }

                if (!getCarrPow(1, ref lev1, ref lev2))
                {
                    return false;
                }

                delta = p1 - lev1;
                if (Math.Abs(delta) <= 0.35)
                {
                    return true;
                }

                if (loop == 0)
                {
                    if (!QueryCarrierAtt(1, ref att))
                    {
                        return false;
                    }

                    cycle = (int)Math.Abs(delta) / 2;
                    cycle += 5;
                }

                if (Math.Abs(delta) >= 2)
                {
                    if (delta > 0)
                    {
                        delta = 2.0;
                    }
                    else
                    {
                        delta = -2.0;
                    }
                }
                else if (Math.Abs(delta) > 1)
                {
                    if (delta > 0)
                    {
                        delta = 1.0;
                    }
                    else
                    {
                        delta = -1.0;
                    }
                }
                else if (Math.Abs(delta) > 0.5)
                {
                    if (delta > 0)
                    {
                        delta = 0.5;
                    }
                    else
                    {
                        delta = -0.5;
                    }
                }
                else
                {
                    if (delta > 0)
                    {
                        delta = 0.25;
                    }
                    else
                    {
                        delta = -0.25;
                    }
                }

                att -= delta;
                att = (int)(att * 100) / 25 * 25;
                att /= 100;
                if (att < 0)
                {
                    att = 0;
                    return true;
                }
                if (!SetCarrierAtt(1, att))
                {
                    return false;
                }

                Thread.Sleep(20);
            }

            if (Math.Abs(p1 - lev1) >= 1.0)
            {
                //return false;
            }

            return true;
        }

        public bool Carrier2Leveling(double p2)
        {
            if (m_isDebug) return true;
            double att = 31.75, delta = 0;
            int cycle = 3;
            byte status = 0;
            double lev1 = 0, lev2 = 0;

            for (int loop = 0; loop < cycle; loop++)
            {

                if (!QueryAlarmStatus(ref status))
                {
                    if (status == 0X02)
                    {
                        m_error = "Over VSWR Alarm";
                    }
                    else if (status == 0X04)
                    {
                        m_error = "Over Driver Alarm";
                    }
                    return false;
                }

                if (!getCarrPow(2, ref lev1, ref lev2))
                {
                    return false;
                }

                delta = p2 - lev2;
                if (Math.Abs(delta) <= 0.35)
                {
                    return true;
                }

                if (loop == 0)
                {
                    if (!QueryCarrierAtt(2, ref att))
                    {
                        return false;
                    }

                    cycle = (int)Math.Abs(delta) / 2;
                    cycle += 5;
                }

                if (Math.Abs(delta) >= 2)
                {
                    if (delta > 0)
                    {
                        delta = 2.0;
                    }
                    else
                    {
                        delta = -2.0;
                    }
                }
                else if (Math.Abs(delta) > 1)
                {
                    if (delta > 0)
                    {
                        delta = 1.0;
                    }
                    else
                    {
                        delta = -1.0;
                    }
                }
                else if (Math.Abs(delta) > 0.5)
                {
                    if (delta > 0)
                    {
                        delta = 0.5;
                    }
                    else
                    {
                        delta = -0.5;
                    }
                }
                else
                {
                    if (delta > 0)
                    {
                        delta = 0.25;
                    }
                    else
                    {
                        delta = -0.25;
                    }
                }

                att -= delta;
                att = (int)(att * 100) / 25 * 25;
                att /= 100;
                if (att < 0)
                {
                    att = 0;
                    return true;
                }
                if (!SetCarrierAtt(2, att))
                {
                    return false;
                }

                Thread.Sleep(20);
            }

            if (Math.Abs(p2 - lev2) >= 1.0)
            {
                //return false;
            }

            return true;
        }
        public bool Reset()
        {//复位
            if (m_isDebug) return true;
            m_msg = "";
            if (!sendMsg("*RST\n", out m_msg))
            {
                return false;
            }

            if (m_msg != "ACK\n")
            {
                return false;
            }

            return true;
        }

        public bool getSwePimTrac(ref Dictionary<string, string> dic, out bool isEND, bool isUp = true)
        {//查询上行扫频互调轨迹："SWE:UP:PIM:TRAC?\n"   下行同理  "SWE:DN:PIM:TRAC?\n"
            /*正常应答：例如“890.0, -122.69, 892.0, -122.37, 894.0, -122.45, 896.0, -122.93\n”（890.0表示上行扫频互调轨迹第一点的频率，-122.69表示上行扫频互调轨迹第一点的互调功率，以下诸如类推）
             */
            isEND = false;
            if (m_isDebug) return true;
            m_error = "";
            string cmd = "";
            if (isUp)
                cmd = string.Format("SWE:UP:PIM:TRAC?\n");
            else
                cmd = string.Format("SWE:DN:PIM:TRAC?\n");
            m_msg = "";
            if (!sendMsg(cmd, out m_msg))
            {
                m_error = "SWE:UP:PIM:TRAC?: sendMsg net error";
                return false;
            }
            if (m_msg.Contains("\n"))
            {//结束上行、下行
                isEND = true;
                m_msg.Replace("\n", "");
            }
            string[] arrRet = m_msg.Split(',');
            if (arrRet.Length > 1)
            {
                for (int i = 0; i < arrRet.Length; i += 2)
                {
                    if (!dic.ContainsKey(arrRet[i]))
                        dic.Add(arrRet[i], arrRet[i + 1]);
                }
            }
            return true;
        }
        public bool getSweCarrFreq(out List<string> F1, out List<string> F2, out bool isEND, bool isUp = true)
        {//查询上行扫频互调轨迹："SWE:UP:CARR:FREQ?\n"
            //正常应答：例如“925.0, 926.0, 927.0, 928.0, 960.0\n”（925.0表示上行扫频互调轨迹第一点载波1的频率，依次类推，928.0表示上行扫频互调轨迹截止点载波1的频率；960.0表示载波2的频率）
            //异常应答：“NAK\n”

            F1 = new List<string>();
            F2 = new List<string>();
            isEND = false;
            if (m_isDebug) return true;
            m_error = "";
            string cmd = "";
            if (isUp)
                cmd = string.Format("SWE:UP:CARR:FREQ?\n");
            else
                cmd = string.Format("SWE:DN:CARR:FREQ?\n");
            m_msg = "";
            if (!sendMsg(cmd, out m_msg))
            {
                m_error = "SWE:UP:CARR:FREQ?: sendMsg net error";
                return false;
            }
            if (m_msg.Contains("\n"))
            {//结束上行、下行
                isEND = true;
                m_msg.Replace("\n", "");
            }
            string[] arrRet = m_msg.Split(',');
            if (arrRet.Length > 1)
            {
                for (int i = F1.Count * 2; i < arrRet.Length; i += 2)
                {
                    F1.Add(arrRet[i]);
                    F2.Add(arrRet[i + 1]);
                }
            }
            return true;
        }
        public bool getSwePoint(ref List<JcPIMRunner.XPlot> lstXPlot, out bool isEND, ref double n1, ref double n2, bool isUp = true)
        {
            m_error = ""; m_msg = ""; isEND = false;
            string cmdF = "", cmdV = "", freq = "", val = "";
            if (isUp)
            {
                /********上行先看下行，下行有数据证明上行完成***************/
                cmdF = "SWE:DN:CARR:FREQ?\n";
                sendMsg(cmdF, out freq);
                if (freq.Split(',').Length > 1)
                {
                    isEND = true;
                }
                /********上行先看下行，下行有数据证明上行完成***************/

                cmdF = "SWE:UP:CARR:FREQ?\n";
                cmdV = "SWE:UP:PIM:TRAC?\n";
            }
            else
            {
                cmdF = "SWE:DN:CARR:FREQ?\n";
                cmdV = "SWE:DN:PIM:TRAC?\n";
            }
            if (!sendMsg(cmdF, out freq) || !sendMsg(cmdV, out val))
            {
                m_error = "SWE:CARR:FREQ?||SWE:PIM:TRAC?: sendMsg net error";
                return false;
            }
            //int co = 0;
            //do
            //{
            //    co++;
            //    sendMsg(cmdF, out freq);
            //    Thread.Sleep(10);
            //    sendMsg(cmdV, out val);
            //    Thread.Sleep(10);
            //}
            //while (freq == "" && val == "");

            //if (freq.Contains("\n") && val.Contains("\n"))
            //{
            //    isEND = true;
            //}
            //freq.Replace("\n", "");
            //val.Replace("\n", "");
            string[] ARRfreq = freq.Split(',');
            if (ARRfreq.Length < 2) return false;
            double[] dsARRfreq = Array.ConvertAll(ARRfreq, v1 => double.Parse(v1));
            string[] ARRval = val.Split(',');
            double[] dsARRval = Array.ConvertAll(ARRval, v1 => double.Parse(v1));
            int start = 0;
            if (isUp)
            {
                start = (int)n1 * 2;
                n1 = ARRfreq.Length / 2;
            }
            else
            {
                start = (int)n2 * 2;
                n2 = ARRfreq.Length / 2;
            }
            for (int i = start; i < ARRfreq.Length; i += 2)
            {
                if (lstXPlot.IndexOf(new JcPIMRunner.XPlot(dsARRfreq[i], dsARRfreq[i + 1], dsARRval[i], dsARRval[i + 1])) < 0)
                    lstXPlot.Add(new JcPIMRunner.XPlot(dsARRfreq[i], dsARRfreq[i + 1], dsARRval[i], dsARRval[i + 1]));
            }
            return true;
        }
        public bool setIMFreqRang(double rxl, double rxh)
        {//            设置互调频率范围："IM:FREQ:RANG XXXX.X,YYYY.Y\n"
            //（注释：XXXX.X 表示互调起始频率，YYYY.Y 表示互调截止频率）
            //正常应答：“ACK\n”
            //异常应答：“NAK\n”
            if (m_isDebug) return true;
            string cmd = "";

            for (int index = 0; index < 2; index++)
            {
                if (index == 0)
                {
                    cmd = String.Format("IM:FREQ:STAR {0:000.000} MHz\n", rxl);
                }
                else
                {
                    cmd = String.Format("IM:FREQ:STOP {0:000.000} MHz\n", rxh);
                }
                m_error = cmd;
                m_msg = "";
                if (!sendMsg(cmd, out m_msg))
                {
                    m_error += "IM:FREQ:RANG : sendMsg net error";
                    return false;
                }

            }
            return true;
        }

        public bool getIMFreq(ref double freq)
        {
            if (m_isDebug) return true;
            string cmd = String.Format("IM:FREQ?\n");
            m_error = cmd;
            m_msg = "";
            if (!sendMsg(cmd, out m_msg))
            {
                m_error += "IM:FREQ? : sendMsg net error";
                return false;
            }
            try
            {
                string[] reply = m_msg.Split(' ');
                freq = Convert.ToDouble(reply[0]);
            }
            catch
            {
                return false;
            }

            return true;
        }
        public bool getErr()
        {
            /*
             * 35.	查询系统错误："SYST:ERR?\n"
正常应答：“XXXXXXXXXXXXXXX\n”（“No Error!\n”表示
无系统错误）
异常应答：“NAK\n”
             */
            if (m_isDebug) return true;
            m_error = ""; m_msg = "";
            string cmd = "SYST:ERR?\n";
            if (!sendMsg(cmd, out m_msg))
            {
                m_error = "SYST:ERR?: sendMsg net error";
                return false;
            }
            else
            {
                m_error = m_msg;
                if (m_msg == "No Error!\n")
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        bool isNAK(out string msg)
        {
            msg = readMsg();
            if (msg == "NAK\n")
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        public string fnGetError()
        {
            return m_error;
        }


        double F1 = 0D;
        double F2 = 0D;
        public bool fnSetTxFreqs(double freq1, double freq2, string unit)
        {
            F1 = ToMhz(freq1, unit);
            F2 = ToMhz(freq2, unit);
            return true;
        }

    }

    class ClsRfPimCmdCom
    {//纳特设备指令集
        /* 串口：波特率115200，校验位无，数据位8，停止位1 */

        /*
        *RST    --ACK
        *FREQ:BAND 0  --ACK
        *IM:FREQ:STAR?  --NAK
        *SYST:MODE REFL/TRAN  --ACK
        *IM:ORD 3  --ACK
        *CARR1:FREQ 1805.000 MHz  --ACK
        *CARR2:FREQ 1880.000 MHz  --ACK
        *CARR1:POW 43.00 dBm  --ACK
        *CARR2:POW 43.00 dBm  --ACK
        *CARR1:ATT 15.00 dB  --ACK
        *CARR2:ATT 15.00 dB  --ACK
        *CARR1:OUTP:STAT ON  --ACK
        *CARR2:OUTP:STAT ON  --ACK
        *ALAR:STAT?  -- 00000000
         
         * 轮循开始
         *CARR1:ATT? --15.00 dB
         *CARR1:POW? --32.18 dB
         *CARR1:ATT 14.00 dB  --ACK
         *CARR1:POW? --33.28 dB
         *CARR1:ATT 13.00 dB  --ACK
         *CARR1:POW? --34.38 dB
         ...
         * CARR1:POW? --43 dB
         *
         *CARR2:ATT? --15.00 dB
         *CARR2:POW? --32.18 dB
         *CARR2:ATT 14.00 dB  --ACK
         *CARR2:POW? --33.28 dB
         *CARR2:ATT 13.00 dB  --ACK
         *CARR2:POW? --34.38 dB
         ...
         *CARR2:POW? --43.00 dB
         * 
        *IM:POW?   -- -134.10 dBm
        *ALAR:STAT?  -- 00000000
        *返回功率调节过程，轮循下一次读值，直至结束
        *CARR1:OUTP:STAT OFF --ACK
        *CARR2:OUTP:STAT OFF --ACK                          
        */
        const int TIMEOUT = 50;
        const string NEW_LINE = "\n";
        bool m_isDebug = false;
        string m_error;
        SerialPort m_portObj;
        double ranMax = -115;
        double ranMin = -120;
        double Tx1 = 0;
        double Tx2 = 0;
        public ClsRfPimCmdCom(bool isDebug = false)
        {
            SetDebug(isDebug);
        }
        public void SetDebug(bool isDebug)
        {
            m_isDebug = isDebug;
        }
        public bool SetTxPower(double tx1, double tx2)
        {
            Tx1 = tx1;
            Tx2 = tx2;
            return true;
        }
        public void SetDebugMaxMin(double max, double min)
        {
            if (max != 0 && min != 0)
            {
                ranMax = max;
                ranMin = min;
            }
            else
            {
                ranMax = -115;
                ranMin = -120;
            }
        }

        public bool Connect(string Name, int baud = 115200, Parity pty = Parity.None, int bit = 8, StopBits stopbit = StopBits.One)
        {
            if (m_isDebug) return true;
            try
            {
                m_portObj = new SerialPort(Name, baud, pty, bit, stopbit);
                //this.m_portObj.ReceivedBytesThreshold = 11;
                //this.m_portObj.DataReceived += new SerialDataReceivedEventHandler(cport_DataReceived);
                m_portObj.Open();
                string idn = getIDN();
                if (idn != null && idn.Split(',')[0] == "Rflight")
                    return true;
                else
                {
                    m_error = "连接对象非纳特仪表";
                    Close();
                    return false;
                }
            }
            catch (Exception ex)
            {
                m_error = ex.Message;
                return false;
            }
        }

        public void Close()
        {
            if (m_isDebug) return;
            if (m_portObj != null)
            {
                if (m_portObj.IsOpen)
                {
                    m_portObj.Close();
                }
            }
        }

        public string getIDN()
        {
            if (m_isDebug) return "";
            string cmd = "*IDN?\n";
            m_portObj.DiscardInBuffer();
            m_portObj.DiscardOutBuffer();
            m_portObj.WriteLine(cmd);
            Thread.Sleep(TIMEOUT);
            string ret = null;
            if (m_portObj.BytesToRead > 0)
                ret = m_portObj.ReadLine();
            return ret;
        }

        public bool Reset()
        {//复位无法重置频段选择 频率设置 FREQ:BAND 0
            if (m_isDebug) return true;
            string cmd = "*RST\n";
            m_portObj.DiscardInBuffer();
            m_portObj.DiscardOutBuffer();
            m_portObj.WriteLine(cmd);
            Thread.Sleep(TIMEOUT);
            string ret = null;
            if (m_portObj.BytesToRead > 0)
                ret = m_portObj.ReadLine();
            if (ret != "ACK")
            {
                m_error = "复位错误";
                return false;
            }
            else return true;
        }

        public int getBandSize()
        {//此命令无效-->试验吉安1800互调仪、编号14042131，返回NAK
            if (m_isDebug) return 0;
            string cmd = "BAND:SIZE?\n";
            m_portObj.DiscardInBuffer();
            m_portObj.DiscardOutBuffer();
            m_portObj.WriteLine(cmd);
            Thread.Sleep(TIMEOUT);
            string ret = null;
            if (m_portObj.BytesToRead > 0)
                ret = m_portObj.ReadLine();
            if (ret == "NAK")
                return -1;
            return Convert.ToInt32(ret);
        }

        public bool setFreqBand(int index = 0)
        {//单一频段默认发0
            if (m_isDebug) return true;
            string cmd = string.Format("FREQ:BAND {0}\n", index);
            m_portObj.DiscardInBuffer();
            m_portObj.DiscardOutBuffer();
            m_portObj.WriteLine(cmd);
            Thread.Sleep(TIMEOUT);
            string ret = null;
            if (m_portObj.BytesToRead > 0)
                ret = m_portObj.ReadLine();
            if (ret != "ACK")
            {
                m_error = "频段设置错误";
                return false;
            }

            if (getFreqBand() != index)
            {
                m_error = "频段设置错误";
                return false;
            }

            return true;
        }

        public int getFreqBand()
        {
            if (m_isDebug) return 0;
            string cmd = string.Format("FREQ:BAND?");
            m_portObj.DiscardInBuffer();
            m_portObj.DiscardOutBuffer();
            m_portObj.WriteLine(cmd);
            Thread.Sleep(TIMEOUT);
            string ret = null;
            if (m_portObj.BytesToRead > 0)
                ret = m_portObj.ReadLine();
            if (ret == "NAK")
            {
                return -1;
            }
            else return Convert.ToInt32(ret);
        }

        public bool setCarrFreq(double f1, double f2, string unit = "mhz")
        {
            if (m_isDebug) return true;
            f1 = ToMhz(f1, unit);
            f2 = ToMhz(f2, unit);
            string cmd = String.Format("CARR{0}:FREQ {1:000.000} MHz\n", 1, f1);
            m_portObj.DiscardInBuffer();
            m_portObj.DiscardOutBuffer();
            m_portObj.WriteLine(cmd);
            Thread.Sleep(TIMEOUT);
            string ret = null;
            if (m_portObj.BytesToRead > 0)
                ret = m_portObj.ReadLine();
            if (ret == "NAK")
            {
                m_error = "载波F1设置错误";
                return false;
            }
            if (f1 != getCarrFreq(1))
            {
                m_error = "载波F1设置错误";
                return false;
            }

            cmd = String.Format("CARR{0}:FREQ {1:000.000} MHz\n", 2, f2);
            m_portObj.DiscardInBuffer();
            m_portObj.DiscardOutBuffer();
            m_portObj.WriteLine(cmd);
            Thread.Sleep(TIMEOUT);
            ret = null;
            if (m_portObj.BytesToRead > 0)
                ret = m_portObj.ReadLine();
            if (ret == "NAK")
            {
                m_error = "载波F2设置错误";
                return false;
            }
            if (f2 != getCarrFreq(2))
            {
                m_error = "载波F2设置错误";
                return false;
            }

            return true;
        }

        public double getCarrFreq(int id = 1)
        {
            if (m_isDebug) return 0;
            string cmd = String.Format("CARR{0}:FREQ?\n", id);
            m_portObj.DiscardInBuffer();
            m_portObj.DiscardOutBuffer();
            m_portObj.WriteLine(cmd);
            Thread.Sleep(TIMEOUT);
            string ret = null;
            if (m_portObj.BytesToRead > 0)
                ret = m_portObj.ReadLine();
            if (ret == "NAK")
            {
                return -1;
            }
            else
            {
                return Convert.ToDouble(ret.Split(' ')[0]);
            }
        }

        public bool QueryAlarmStatus(ref byte status)
        {//告警状态
            if (m_isDebug) return true;
            string cmd = "ALAR:STAT?\n";
            m_portObj.DiscardInBuffer();
            m_portObj.DiscardOutBuffer();
            m_portObj.WriteLine(cmd);
            Thread.Sleep(TIMEOUT);
            string ret = null;
            if (m_portObj.BytesToRead > 0)
                ret = m_portObj.ReadLine();
            if (ret == "NAK")
            {
                return false;
            }

            //试验吉安1800互调仪、编号14042131  返回为8位
            //if (ret.Length != 9)
            //{
            //    return false;
            //}

            status = 0;
            for (int index = 0; index < 8; index++)
            {
                if ((ret[index] > 0x31) || (ret[index] < 0x30))
                {
                    return false;
                }

                if (ret[index] == 0x31)
                {
                    status |= (byte)(0x01 << (7 - index));
                }
            }

            return true;
        }

        public bool QueryCarrierAtt(int source, ref double att)
        {//衰减量
            if (m_isDebug) return true;
            string tbuf = String.Format("CARR{0}:ATT?\n", source);
            m_portObj.DiscardInBuffer();
            m_portObj.DiscardOutBuffer();
            m_portObj.WriteLine(tbuf);
            Thread.Sleep(TIMEOUT);
            string ret = null;
            if (m_portObj.BytesToRead > 0)
                ret = m_portObj.ReadLine();
            if (ret == "NAK")
            {
                return false;
            }

            try
            {
                string[] reply = ret.Split(' ');
                att = Convert.ToDouble(reply[0]);
            }
            catch
            {
                return false;
            }

            return true;
        }
        public bool SetCarrierAtt(int source, double att)
        {//衰减器
            if (m_isDebug) return true;
            string tbuf = String.Format("CARR{0}:ATT {1:00.00} dB\n", source, att);
            m_portObj.DiscardInBuffer();
            m_portObj.DiscardOutBuffer();
            m_portObj.WriteLine(tbuf);
            Thread.Sleep(TIMEOUT);
            string ret = null;
            if (m_portObj.BytesToRead > 0)
                ret = m_portObj.ReadLine();
            if (ret == "NAK")
            {
                m_error = "衰减器设置错误";
                return false;
            }
            return true;
        }

        public bool Carrier1Leveling(double p1)
        {//自动调节载波功率
            if (m_isDebug) return true;
            double att = 31.75, delta = 0;
            int cycle = 3;
            byte status = 0;
            double lev1 = 0, lev2 = 0;

            for (int loop = 0; loop < cycle; loop++)
            {

                if (!QueryAlarmStatus(ref status))
                {
                    if (status == 0X02)
                    {
                        m_error = "Over VSWR Alarm";
                    }
                    else if (status == 0X04)
                    {
                        m_error = "Over Driver Alarm";
                    }
                    return false;
                }

                if (!getCarrPow(1, ref lev1, ref lev2))
                {
                    return false;
                }

                delta = p1 - lev1;
                if (Math.Abs(delta) <= 0.35)
                {
                    return true;
                }

                if (loop == 0)
                {
                    if (!QueryCarrierAtt(1, ref att))
                    {
                        return false;
                    }

                    cycle = (int)Math.Abs(delta) / 2;
                    cycle += 5;
                }

                if (Math.Abs(delta) >= 2)
                {
                    if (delta > 0)
                    {
                        delta = 2.0;
                    }
                    else
                    {
                        delta = -2.0;
                    }
                }
                else if (Math.Abs(delta) > 1)
                {
                    if (delta > 0)
                    {
                        delta = 1.0;
                    }
                    else
                    {
                        delta = -1.0;
                    }
                }
                else if (Math.Abs(delta) > 0.5)
                {
                    if (delta > 0)
                    {
                        delta = 0.5;
                    }
                    else
                    {
                        delta = -0.5;
                    }
                }
                else
                {
                    if (delta > 0)
                    {
                        delta = 0.25;
                    }
                    else
                    {
                        delta = -0.25;
                    }
                }

                att -= delta;
                att = (int)(att * 100) / 25 * 25;
                att /= 100;
                if (att < 0)
                {
                    att = 0;
                    return true;
                }
                if (!SetCarrierAtt(1, att))
                {
                    return false;
                }

                Thread.Sleep(20);
            }

            if (Math.Abs(p1 - lev1) >= 1.0)
            {
                //return false;
            }

            return true;
        }

        public bool Carrier2Leveling(double p2)
        {//自动调节载波功率
            if (m_isDebug) return true;
            double att = 31.75, delta = 0;
            int cycle = 3;
            byte status = 0;
            double lev1 = 0, lev2 = 0;

            for (int loop = 0; loop < cycle; loop++)
            {

                if (!QueryAlarmStatus(ref status))
                {
                    if (status == 0X02)
                    {
                        m_error = "Over VSWR Alarm";
                    }
                    else if (status == 0X04)
                    {
                        m_error = "Over Driver Alarm";
                    }
                    return false;
                }

                if (!getCarrPow(2, ref lev1, ref lev2))
                {
                    return false;
                }

                delta = p2 - lev2;
                if (Math.Abs(delta) <= 0.35)
                {
                    return true;
                }

                if (loop == 0)
                {
                    if (!QueryCarrierAtt(2, ref att))
                    {
                        return false;
                    }

                    cycle = (int)Math.Abs(delta) / 2;
                    cycle += 5;
                }

                if (Math.Abs(delta) >= 2)
                {
                    if (delta > 0)
                    {
                        delta = 2.0;
                    }
                    else
                    {
                        delta = -2.0;
                    }
                }
                else if (Math.Abs(delta) > 1)
                {
                    if (delta > 0)
                    {
                        delta = 1.0;
                    }
                    else
                    {
                        delta = -1.0;
                    }
                }
                else if (Math.Abs(delta) > 0.5)
                {
                    if (delta > 0)
                    {
                        delta = 0.5;
                    }
                    else
                    {
                        delta = -0.5;
                    }
                }
                else
                {
                    if (delta > 0)
                    {
                        delta = 0.25;
                    }
                    else
                    {
                        delta = -0.25;
                    }
                }

                att -= delta;
                att = (int)(att * 100) / 25 * 25;
                att /= 100;
                if (att < 0)
                {
                    att = 0;
                    return true;
                }
                if (!SetCarrierAtt(2, att))
                {
                    return false;
                }

                Thread.Sleep(20);
            }

            if (Math.Abs(p2 - lev2) >= 1.0)
            {
                //return false;
            }

            return true;
        }

        public bool getCarrPow(int source, ref double p1, ref double p2)
        {
            if (m_isDebug)
            {
                p1 = Tx1;
                p2 = Tx2;
                return true;
            }
            string cmd = String.Format("CARR{0}:POW?\n", source);
            m_portObj.DiscardInBuffer();
            m_portObj.DiscardOutBuffer();
            m_portObj.WriteLine(cmd);
            Thread.Sleep(TIMEOUT);
            string ret = null;
            if (m_portObj.BytesToRead > 0)
                ret = m_portObj.ReadLine();
            if (ret == "NAK")
            {
                m_error = "获取功率错误";
                return false;
            }
            else
            {
                try
                {
                    string[] reply = ret.Split(' ');
                    if (source == 1)
                    {
                        p1 = Convert.ToDouble(reply[0]);
                    }
                    else
                    {
                        p2 = Convert.ToDouble(reply[0]);
                    }
                }
                catch
                {
                    m_error = "获取功率错误";
                    return false;
                }
            }
            return true;
        }

        public bool setCarrOutp(bool output = true)
        {
            if (m_isDebug) return true;
            string outStat = "";
            if (output)
                outStat = "ON";
            else
                outStat = "OFF";
            string cmd = String.Format("CARR{0}:OUTP:STAT {1}\n", 1, outStat);
            m_portObj.DiscardInBuffer();
            m_portObj.DiscardOutBuffer();
            m_portObj.WriteLine(cmd);
            Thread.Sleep(TIMEOUT);
            string ret = null;
            if (m_portObj.BytesToRead > 0)
                ret = m_portObj.ReadLine();
            if (ret == "NAK")
            {
                m_error = "第一路载波功率输出设置错误";
                return false;
            }

            cmd = String.Format("CARR{0}:OUTP:STAT {1}\n", 2, outStat);
            m_portObj.DiscardInBuffer();
            m_portObj.DiscardOutBuffer();
            m_portObj.WriteLine(cmd);
            Thread.Sleep(TIMEOUT);
            ret = null;
            if (m_portObj.BytesToRead > 0)
                ret = m_portObj.ReadLine();
            if (ret == "NAK")
            {
                m_error = "第二路载波功率输出设置错误";
                return false;
            }

            return true;
        }

        public bool setSystMode(string port)
        {//测量端口。设置反射端口 SYST:MODE 0\n  SYST:MODE 1\n，在试验吉安1800互调仪、编号14042131，返回NAK
            if (m_isDebug) return true;
            if (port == "0")
            {
                port = "REFL";
            }
            else if (port == "1")
            {
                port = "TRAN";
            }

            string cmd = string.Format("SYST:MODE {0}\n", port);
            m_portObj.DiscardInBuffer();
            m_portObj.DiscardOutBuffer();
            m_portObj.WriteLine(cmd);
            Thread.Sleep(TIMEOUT);
            string ret = null;
            if (m_portObj.BytesToRead > 0)
                ret = m_portObj.ReadLine();
            if (ret == "NAK")
            {
                m_error = "测量模式设置错误";
                return false;
            }
            //if (port != getSystMode())
            //{
            //    m_error = "测量模式设置错误";
            //}
            /*机械开关稳定时间至少300ms*/
            Thread.Sleep(300);
            return true;
        }

        public string getSystMode()
        {
            if (m_isDebug) return "";
            string cmd = string.Format("SYST:MODE?\n");
            m_portObj.DiscardInBuffer();
            m_portObj.DiscardOutBuffer();
            m_portObj.WriteLine(cmd);
            Thread.Sleep(TIMEOUT);
            string ret = null;
            if (m_portObj.BytesToRead > 0)
                ret = m_portObj.ReadLine();
            if (ret == "NAK")
            {
                return null;
            }
            return ret;
        }

        public bool setImOrd(int order = 3)
        {
            if (m_isDebug) return true;
            string cmd = string.Format("IM:ORD {0}\n", order);
            m_portObj.DiscardInBuffer();
            m_portObj.DiscardOutBuffer();
            m_portObj.WriteLine(cmd);
            Thread.Sleep(TIMEOUT);
            string ret = null;
            if (m_portObj.BytesToRead > 0)
                ret = m_portObj.ReadLine();
            if (ret == "NAK")
            {
                m_error = "互调阶数设置错误";
                return false;
            }
            if (order != getImOrd())
            {
                m_error = "互调阶数设置错误";
                return false;
            }
            return true;
        }

        public int getImOrd()
        {
            if (m_isDebug) return 0;
            string cmd = string.Format("IM:ORD?\n");
            m_portObj.DiscardInBuffer();
            m_portObj.DiscardOutBuffer();
            m_portObj.WriteLine(cmd);
            Thread.Sleep(TIMEOUT);
            string ret = null;
            if (m_portObj.BytesToRead > 0)
                ret = m_portObj.ReadLine();
            if (ret == "NAK")
            {
                return -1;
            }
            try
            {
                return Convert.ToInt32(ret);
            }
            catch
            {
                return -1;
            }
        }

        public bool getImPow(ref double dPimResult)
        {
            if (m_isDebug)
            {
                Random ran = new Random(Guid.NewGuid().GetHashCode());
                int min = (int)(ranMin * 10);
                int max = (int)(ranMax * 10);
                dPimResult = ran.Next(min, max) / 10 + ran.NextDouble();
                dPimResult = Math.Round(dPimResult, 2);
                return true;
            }
            string cmd = string.Format("IM:POW?\n");
            m_portObj.DiscardInBuffer();
            m_portObj.DiscardOutBuffer();
            m_portObj.WriteLine(cmd);
            Thread.Sleep(TIMEOUT);
            string ret = null;
            if (m_portObj.BytesToRead > 0)
                ret = m_portObj.ReadLine();
            if (ret == "NAK")
            {
                m_error = "获取互调功率dbm错误";
                return false;
            }
            else
            {
                try
                {
                    string[] reply = ret.Split(' ');
                    dPimResult = Convert.ToDouble(reply[0]);
                }
                catch
                {
                    m_error = "获取互调功率dbm错误";
                    return false;
                }
            }
            return true;
        }

        double ToMhz(double freq, string unit)
        {
            if (unit.ToLower() == ("ghz"))
            {
                freq *= 1000;
            }
            else if (unit.ToLower() == ("khz"))
            {
                freq /= 1000;
            }
            else if (unit.ToLower() == ("hz"))
            {
                freq /= 1000 * 1000;
            }
            else//默认为mhz
            { }
            return Math.Round(freq, 1);
        }

        public string fnGetError()
        {
            return m_error;
        }


    }
}
